<?php

namespace App\Models\Traits;

use Illuminate\Database\Eloquent\Builder;

trait Filters
{
    /**
     * 过滤
     *
     * @param Builder $query
     * @param [type] $attributes
     * @return void
     */
    public function scopeFilters(Builder $query, $attributes)
    {

        collect($attributes)->each(function ($attr) use ($query) {
            $query->myFilter($attr);
        });

        return $query;
    }

    /**
     * 单个过滤
     *
     * @param Builder $query
     * @param [type] $attr
     * @return void
     */
    public function scopeMyFilter(Builder $query, $attr)
    {

        return $query->when($attr[2], function ($query, $value) use ($attr) {

            if ($attr[1] === 'like') {
                $value = "%{$value}%";
            }

            $query->where($attr[0], $attr[1], $value);
        });
    }
}
